<template>
  <div>
    <!--导出-->
    <Modal
      v-model="modal1"
      title="导出"
      @on-ok="exportExcel"
      @on-cancel="modal1=false">
      <CheckboxGroup v-model="selectValue">
        <Checkbox v-for="(item,index) in columns"
                  v-if="item.type !== 'index' && item.type !== 'selection' && item.type !== 'expand' && item.type !== 'html'&& item.options===undefined"
                  :key="index"
                  :label="item.key">
          <span>{{item.title}}</span>
        </Checkbox>
      </CheckboxGroup>
    </Modal>
    <!--查询-->
    <Card v-if="hasTools('search')">
      <Row :gutter="16">
        <Col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" v-for="(item, index) in columns" :key="index"
             v-if="item.searchType!==undefined" style="padding-top: 3px;padding-bottom: 3px">
          <Input v-model="searchForm[item.key==='handle'?item.key2:item.key]" clearable @on-clear="multiSearch"
                 v-if="item.searchType==='input'" type="text" :placeholder="item.title">
          </Input>
          <Input v-model="searchForm[item.key==='handle'?item.key2:item.key]" clearable @on-clear="multiSearch"
                 v-if="item.searchType==='number'" type="number" :placeholder="item.title">
          </Input>
          <Select clearable transfer style="min-width: 100px"
                  v-model="searchForm[item.key==='handle'?item.key2:item.key]"
                  @on-clear="multiSearch" v-if="item.searchType==='select'">
            <Option v-for="(op,i) in item.data" :value="op.value" :key="i">{{ op.key }}</Option>
          </Select>
          <DatePicker transfer v-model="searchForm[item.key==='handle'?item.key2:item.key]"
                      v-if="item.searchType==='date'" type="date" format="yyyy-MM-dd HH:mm" :placeholder="item.title"
                      style="width: 100%"></DatePicker>
          <DatePicker transfer v-model="searchForm[item.key==='handle'?item.key2:item.key]"
                      v-if="item.searchType==='daterange'" type="daterange" format="yyyy-MM-dd"
                      :placeholder="item.title"
                      style="width: 100%"></DatePicker>
          <DatePicker transfer v-model="searchForm[item.key==='handle'?item.key2:item.key]"
                      v-if="item.searchType==='datetime'" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                      :placeholder="item.title"
                      style="width: 100%"></DatePicker>
          <DatePicker transfer v-model="searchForm[item.key==='handle'?item.key2:item.key]"
                      v-if="item.searchType==='datetimerange'" type="datetimerange" format="yyyy-MM-dd HH:mm:ss"
                      :placeholder="item.title" style="width: 100%"></DatePicker>
          <DatePicker transfer v-model="searchForm[item.key==='handle'?item.key2:item.key]"
                      v-if="item.searchType==='year'" type="year" format="yyyy-MM-dd" :placeholder="item.title"
                      style="width: 100%"></DatePicker>
          <DatePicker transfer v-model="searchForm[item.key==='handle'?item.key2:item.key]"
                      v-if="item.searchType==='month'" type="month" format="yyyy-MM-dd"
                      :placeholder="item.title"></DatePicker>
        </Col>
        <Col :xl="12" :lg="6" :md="24" :sm="24" :xs="24" style="padding-top: 3px;padding-bottom: 3px">
          <Button  shape="circle" type="primary" icon="ios-search" @click="multiSearch">查询</Button>
          <Button style="margin-left: 15px"  shape="circle" type="info" icon="ios-refresh" @click="resetSearch">重置</Button>
        </Col>
      </Row>
    </Card>
    <Card :class="hasTools('search')?'top-ten':''">
      <Row>
        <div style="float: left">
          <slot name="buttons"></slot>
        </div>
       <div style="float: right">
          <Row>
            <Tooltip v-if="hasTools('refresh')" content="刷新" transfer placement="top"
                     style="margin-left: 0px;margin-top: 6px;float: right">
              <Icon :class="isLoading?'demo-spin-icon-load':''" type="ios-refresh" :size="defaultSize"
                    color="defaultColor" @click="refreshTable"></Icon>
            </Tooltip>
            <Tooltip v-if="hasTools('export')" content="导出" transfer placement="top"
                     style="margin-left: 5px;margin-top: 3px;float: right">
              <Icon type="ios-download-outline" :size="defaultSize" color="defaultColor" @click="showExport"></Icon>
            </Tooltip>
            <Tooltip v-if="hasTools('import')" content="导入" transfer placement="top"
                     style="margin-left: 5px;margin-top: 3px;float: right">
              <Upload id="import" v-show="false" action="" :before-upload="handleBeforeUpload" accept=".xls, .xlsx">
              </Upload>
              <Icon type="ios-cloud-upload-outline" :size="defaultSize" color="defaultColor"
                    @click="initUpload">
              </Icon>
            </Tooltip>
            <Input v-if="hasTools('easySearch')" style="width: 200px;float: right;margin-right: 5px" enter-button v-model="page.q" search
                   :placeholder="easySearchPlaceholder"
                   @on-search="search"/>
          </Row>
        </div>
      </Row>
      <tables style="margin-top: 5px;" ref="tables" :editable="editable" :loading="isLoading" v-model="tableData" :columns="columns"
              :border="border"
              @on-btn="btnClick"
              @on-select="select"
              @on-sort-change="sortMethod"
              @on-row-click="onRowClick"
              @on-row-dblclick="onRowDblclick"
      />
      <Row style="margin-top: 20px" v-if="file===null">
        <Col span="24" v-if="pageLimit">
          <Page style="float: right" :total="page.totalCount" :current="page.currPage" :page-size="page.pageSize"
                show-elevator
                @on-change="changePage" @on-page-size-change="changeSize" show-sizer show-total></Page>
          <div style="clear: both"></div>
        </Col>
      </Row>
    </Card>
  </div>
</template>

<script>
import Tables from '_c/tables'
import CommonIcon from '_c/common-icon'
import excel from '@/libs/excel'
import FormTable from '@/components/form-table'
import { getRequestData } from '../../api/commons'

export default {
  name: 'e-table',
  components: {
    Tables,
    FormTable,
    CommonIcon
  },
  props: {
    border: {
      type: Boolean,
      default: true
    },
    editable: {
      type: Boolean,
      default: false
    },
    tools: {
      type: Array,
      default () {
        return []
      }
    },
    outType: {
      type: String,
      return: 'sx'
    },
    pageLimit: {
      type: Boolean,
      default: true
    },
    defaultColor: {
      type: String,
      default: '#000000'
    },
    defaultSize: {
      type: Number,
      default: 30
    },
    easySearchPlaceholder: {
      type: String,
      return: ''
    },
    columns: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      u: '',
      searchForm: {},
      selectRow: [],
      data: {},
      selectValue: [],
      modal1: false,
      url: '',
      file: null,
      isLoading: false,
      tableData: [],
      page: {
        currPage: 1,
        pageSize: 10,
        totalCount: 0,
        q: '',
        sidx: '',
        order: ''
      }
    }
  },
  methods: {
    getState () {
      return this.isLoading
    },
    multiSearch () {
      let u = ''
      for (let i in this.searchForm) {
        if (typeof this.searchForm[i] === 'string' || typeof this.searchForm[i] === 'number') {
          u = u + i + '=' + this.searchForm[i] + '&'
        } else if (typeof this.searchForm[i] === 'object') {
          if (typeof this.searchForm[i][0] === 'object' && this.searchForm[i][0].getTime() !== '') {
            u = u + i + '=' + this.searchForm[i][0].getTime() + ',' + this.searchForm[i][1].getTime() + '&'
          }
        }
      }

      u = encodeURI(u)
      this.init(this.url, u)
    },
    resetSearch () {
      this.searchForm = {}
      this.init()
    },
    select (params) {
      this.selectRow = params
    },
    onRowClick (row, index) {
      this.$emit('on-row-click', row, index)
    },
    onRowDblclick (row, index) {
      this.$emit('on-row-dblclick', row, index)
    },
    getSelect () {
      return this.selectRow
    },
    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
        this.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    // 读取文件
    readFile (file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
      }
      reader.onprogress = e => {
        // this.progressPercent = Math.round(e.loaded / e.total * 100)
      }
      reader.onerror = e => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = e => {
        this.$Message.info('文件读取成功')
        const data = e.target.result
        const { results } = excel.read(data, 'array')
        this.tableData = this.changeData(results)
        this.isLoading = false
      }
    },
    changeData (arr) {
      let r = []
      for (let i = 0; i < arr.length; i++) {
        let a = JSON.stringify(arr[i])
        for (let i = 0; i < this.columns.length; i++) {
          if (this.columns[i].type !== 'index' && this.columns[i].type !== 'selection' && this.columns[i].type !== 'expand' && this.columns[i].type !== 'html' && this.columns[i].options === undefined) {
            a = a.replace(this.columns[i].title, this.columns[i].key)
          }
        }
        r[i] = JSON.parse(a)
      }
      return r
    },
    initUpload () {
      let myElement = document.getElementById('import')
      let s = myElement.getElementsByTagName('input')
      s[0].click()
      this.file = null
      this.tableData = []
    },
    showExport () {
      this.modal1 = true
    },
    exportExcel () {
      if (this.tableData.length) {
        let titles = []
        for (let i = 0; i < this.selectValue.length; i++) {
          for (let j = 0; j < this.columns.length; j++) {
            if (this.selectValue[i] === this.columns[j].key) {
              titles[i] = this.columns[j].title
            }
          }
        }
        if (this.outType === 'xlsx') {
          const params = {
            title: titles,
            key: this.selectValue,
            data: this.tableData,
            autoWidth: true,
            filename: '导出文件'
          }
          excel.export_array_to_excel(params)
        } else {
          this.$refs.tables.exportCsv({
            filename: `table-${(new Date()).valueOf()}.csv`,
            data: this.tableData,
            columns: this.selectValue,
            noHeader: false
          })
        }
      } else {
        this.$Message.info('表格数据不能为空！')
      }
    },
    refreshTable () {
      this.init(this.url, this.u)
    },
    search () {
      this.init()
    },
    toLine (name) {
      return name.replace(/([A-Z])/g, '_$1').toLowerCase()
    },
    sortMethod (column) {
      this.page.order = column.order
      this.page.sidx = column.column.alias + '.' + this.toLine(column.key)
      this.init(this.url)
    },
    changePage (index) {
      this.page.currPage = index
      this.init(this.url)
    },
    changeSize (index) {
      this.page.pageSize = index
      this.init(this.url)
    },
    btnClick (name, params, action) {
      this.$emit('btnClick', name, params, action)
    },
    hasTools (name) {
      return this.tools.indexOf(name) !== -1
    },
    init (url, u) {
      this.isLoading = true
      if (url !== undefined) {
        if (u !== undefined) {
          this.u = u
          url = url + u
        } else {
          this.url = url
        }
        if (this.pageLimit === false) {
          this.page.pageSize = 1000000000
        }
        getRequestData(url, this.page).then(res => {
          this.tableData = res.page.list
          this.page.currPage = res.page.currPage
          this.page.totalCount = res.page.totalCount
          this.isLoading = false
        })
      } else {
        getRequestData(this.url, this.page).then(res => {
          this.tableData = res.page.list
          this.page.currPage = res.page.currPage
          this.page.totalCount = res.page.totalCount
          this.isLoading = false
        })
      }
    }
  }
}
</script>

<style scoped>
  .demo-spin-icon-load {
    animation: ani-demo-spin 0.5s linear infinite;
  }
  .top-ten{
    margin-top: 10px;
  }
  @keyframes ani-demo-spin {
    from {
      transform: rotate(0deg);
    }
    50% {
      transform: rotate(180deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
</style>
